//
//  BDJianHuoHomeViewController.m
//  BeidouMall
//
//  Created by qie on 16/4/15.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDJianHuoHomeViewController.h"
#import "BDNavigationController.h"
#import "BDAddrMyViewController.h"
#import "BDLoginTableViewController.h"
#import "BDPaySuccessViewController.h"
#import "BDOrderHomeViewController.h"

@interface BDJianHuoHomeViewController () <UIWebViewDelegate,BDPaySuccessViewControllerDelegate>
{
    BOOL reloadWebView;
    BOOL viewOrderList;
    UIWebView *_webView;
}

@property (nonatomic,strong) WebViewJavascriptBridge* bridge;
@end

@implementation BDJianHuoHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = YES;
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0, kScreen_Width, kScreen_Height)];
    //_webView.opaque = NO;// webview不透明
    _webView.backgroundColor = [UIColor clearColor];
    _webView.scalesPageToFit = YES;
//    _webView.delegate = self;
    [self.view addSubview:_webView];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[[BDNetworking shareInstance] baseUrl],JianHuo];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];//从服务端获取数据，忽略本地缓存
    [_webView loadRequest:request];
    
    [self webViewSettings];
    
    UIView *statusView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 20)];
    statusView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:statusView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (![_webView isLoading] && reloadWebView) {
        [_webView reload];
        reloadWebView = NO;
    }
    if (viewOrderList) {
        UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        BDNavigationController *nav_orderVc = [stroyboard instantiateViewControllerWithIdentifier:@"NavOrderStoryboardID"];
        BDOrderHomeViewController *orderVc = (BDOrderHomeViewController *)nav_orderVc.topViewController;
        orderVc.block = ^(NSString *str){
            if ([str isEqualToString:@"success"]) {
                self.tabBarController.selectedIndex = 0;
            }
        };
        [self presentViewController:nav_orderVc animated:YES completion:nil];
        viewOrderList = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)webViewSettings {
    // 开启WVJB LOG
    [WebViewJavascriptBridge enableLogging];
    // 实例化WebViewJavascriptBridge并且带上一个UIWebView
    _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView];
    //不加这个会将当前的webViewDelegate屏蔽
    [_bridge setWebViewDelegate:self];
    
    // js调oc方法（可以通过data给oc方法传值，使用responseCallback将值再返回给js）
    [_bridge registerHandler:@"OC_authorization" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"js传过来的值: %@", data);
        dispatch_async(dispatch_get_main_queue(), ^{// 更新UI操作必须在主线程
            if (![BDAccountManagerModel shareInstance].login) {
                UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                BDNavigationController *nav_addrVc = [stroyboard instantiateViewControllerWithIdentifier:@"navLoginStoryboardID"];
                BDLoginTableViewController *loginVc = (BDLoginTableViewController *)nav_addrVc.topViewController;
                loginVc.isJavascript = YES;
                [self presentViewController:nav_addrVc animated:YES completion:nil];
                loginVc.block = ^(NSString *str){
                    reloadWebView = YES;
                    responseCallback(str);
                };
            } else {
                NSDictionary *dic = @{@"authorization":[BDAccountManagerModel shareInstance].authorization
                                      ,@"userId":[BDAccountManagerModel shareInstance].userId};
                NSString *json = [NSString DataTOjsonString:dic];
                responseCallback(json);
            }
        });
    }];
    // js调oc方法（可以通过data给oc方法传值，使用responseCallback将值再返回给js）
    [_bridge registerHandler:@"OCMethod" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"js传过来的值123: %@", data);
        dispatch_async(dispatch_get_main_queue(), ^{
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
            BDNavigationController *nav_addrVc = [stroyboard instantiateViewControllerWithIdentifier:@"AddrStoryboardID"];
            BDAddrMyViewController *addrVc = (BDAddrMyViewController *)nav_addrVc.topViewController;
            addrVc.flag = @"clickable";
            [self presentViewController:nav_addrVc animated:YES completion:nil];
            addrVc.block = ^(NSString *str){
                responseCallback(str);
            };
        });
    }];
    [_bridge registerHandler:@"OCPay" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"js传过来的值Pay: %@", data);
        NSDictionary *dic = (NSDictionary *)data;
        NSString *order = dic[@"key"];
        [self aliPayWithOrder:order Callback:^(NSDictionary *results) {
            NSLog(@"支付结果reslut = %@",results);
            dispatch_async(dispatch_get_main_queue(), ^{
                NSInteger code = [[results valueForKey:@"resultStatus"] integerValue];
                NSString *type;
                if (code == 9000) {
                    type = @"success";
                } else {
                    type = @"fail";
                }
                UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                BDNavigationController *nav_payVc = [stroyboard instantiateViewControllerWithIdentifier:@"PaySuccessStroyboardID"];
                BDPaySuccessViewController *payVc = (BDPaySuccessViewController *)nav_payVc.topViewController;
                payVc.type = type;
                payVc.myDelegate = self;
                [self presentViewController:nav_payVc animated:YES completion:nil];
                viewOrderList = YES;
                responseCallback(nil);
            });
            
        }];
    }];
    [_bridge registerHandler:@"OCAddress" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"js传过来的值123: %@", data);
        dispatch_async(dispatch_get_main_queue(), ^{
            responseCallback([BDAccountManagerModel shareInstance].inBoundary);
        });
    }];
}

- (void)refreshWebView {
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[[BDNetworking shareInstance] baseUrl],JianHuo];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)aliPayWithOrder:(NSString *) order Callback:(void(^)(NSDictionary *results))callBack {
    //应用注册scheme 便于支付结束后重新打开客户端
    NSString *appScheme = @"BeidouMall";
    NSLog(@"签名字符串:%@",order);
    [[AlipaySDK defaultService] payOrder:order fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        callBack(resultDic);
    }];
}

#pragma mark - BDPaySuccessViewControllerDelegate

- (void)payFinishRefreshWebView {
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[[BDNetworking shareInstance] baseUrl],JianHuo];
    NSURL *url = [NSURL URLWithString:urlStr];
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
}

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSArray *arr = [request.URL.absoluteString componentsSeparatedByString:@"/"];
    NSString *page = arr[arr.count - 1];
    NSLog(@"page = %@",page);
    if ([page containsString:@"index.html"]) {
        self.tabBarController.selectedIndex = 0;
        return NO;
    }
    if ([page containsString:@"details.html"]) {
        
    }
    if ([page containsString:@"pay.html"]) {
        
    }
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"开始加载");
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    NSString *title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"加载完毕 %@",title);
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"加载错误%@",[error localizedDescription]);
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
